package com.global.college.utils;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import androidx.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.global.college.R;
import com.global.college.base.BaseApplication;
import com.global.college.ui.activity.HsLagelDetailActivity;
import com.global.college.widget.HnLoadingDialog;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by fu on 2020/2/21.
 * Describe: 工具类
 */
public class CommonUtils {
    private static final String TAG = CommonUtils.class.getSimpleName();
    private final static SimpleDateFormat FORMAT_Y_M_D = new SimpleDateFormat("yyyy-MM-dd");


    /**
     * 获取当前APP的版本号
     */
    public static int getVersionCode(Context context) {
        int versionCode = 1;
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            versionCode = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static int dpToPxInt(Context context,float dp) {
        return (int) (dpToPx(context,dp) + 0.5f);
    }

    public static float dpToPx(Context context,float dp) {
        return dp * context.getApplicationContext().getResources().getDisplayMetrics().density;
    }


    /**
     * 获取状态栏高度
     * @param context 上下文
     * @return 状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        try {
            Class<?> c = Class.forName("com.android.internal.R$dimen");
            Object o = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = (Integer) field.get(o);
            return context.getResources().getDimensionPixelSize(x);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 获取当前APP的版本名称
     */
    public static String getVersionNameNotV(Context context) {
        String VersionName = "1.0.0";
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            VersionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return VersionName;

    }

    /**
     * 获取当前APP的版本名称
     */
    public static String getVersionName(Context context) {
        String VersionName = "V1.0.0";
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            VersionName = "V" + packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return VersionName;
    }

    /**
     * 得到应用程序的包名
     */
    public static String getPackageName() {
        return BaseApplication.getContext().getPackageName();
    }


    /**
     * 创建指定数量的随机字符串
     *
     * @param numberFlag 是否是数字
     * @param length
     * @return
     */
    public static String createRandom(boolean numberFlag, int length) {
        String retStr = "";
        String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }



    /**
     * 获取手机唯一标识
     *
     * @return
     */
    public static String getUniqueid(Context context) {
        String uniqueid = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        return uniqueid;
    }


    /**
     * 根据传入的类(class)打开指定的activity
     *
     * @param pClass
     */
    public static void openActivity(Class<?> pClass, Bundle bundle, Context context) {
        Intent itent = new Intent();
        itent.setClass(context, pClass);
        if (bundle != null) {
            itent.putExtras(bundle);
        }
        itent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(itent);
    }

    /**
     * 隐藏软键盘(有输入框)
     * @param context
     * @param mEditText
     */
    public static void hideSoftKeyboard(@NonNull Context context,
                                        @NonNull EditText mEditText)
    {
        InputMethodManager inputmanger = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }

    /**
     * 打开软键盘
     *
     * @param mEditText
     * @param mContext
     */
    public static void openKeybord(EditText mEditText, Context mContext) {
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEditText, InputMethodManager.RESULT_SHOWN);
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
                InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 判断当前软键盘是否打开
     *
     * @param activity
     * @return
     */
    public static boolean isSoftInputShow(Activity activity) { // 虚拟键盘隐藏 判断view是否为空
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            // 隐藏虚拟键盘
            InputMethodManager inputmanger = (InputMethodManager) activity .getSystemService(Activity.INPUT_METHOD_SERVICE);

            return inputmanger.isActive() && activity.getWindow().getCurrentFocus() != null;
        } return false;
    }

    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }


    public static boolean isPad(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

    /**
     * 将view转化为bitmap
     */
    public static Bitmap view2Bitmap(final View view) {
        if (view == null) return null;
        Bitmap ret = Bitmap.createBitmap(view.getWidth(),
                view.getHeight(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(ret);
        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(canvas);
        } else {
            canvas.drawColor(Color.WHITE);
        }
        view.draw(canvas);
        return ret;
    }

    // 两次点击按钮之间的点击间隔不能少于1500毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1500;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 使用ProgressBar实现的进度动画
     */
    public static HnLoadingDialog progressLoading(Context context, String msg, DialogInterface.OnCancelListener cancelListener) {
        HnLoadingDialog loading = new HnLoadingDialog(context, R.style.loading);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_loading_pb, null);
        if (!TextUtils.isEmpty(msg)) {
            TextView tvMsg = (TextView) view.findViewById(R.id.tv_load_msg);
            tvMsg.setText(msg);
        }
        loading.addContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        loading.setTag(msg);
        loading.setCancelable(true);// 点击返回键关闭
        loading.setCanceledOnTouchOutside(false);// 点击外部关闭
        loading.setOnCancelListener(cancelListener);
        return loading;
    }

    /**
     * 使用Drawable实现的进度动画
     */
    public static HnLoadingDialog drawableLoading(Context context, String tag, DialogInterface.OnCancelListener cancelListener) {
        AnimationDrawable aniDraw;
        HnLoadingDialog loading = new HnLoadingDialog(context, R.style.loading);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.dialog_loading, null);
        ImageView loadView = (ImageView) view.findViewById(R.id.loadingImageView);
        aniDraw = (AnimationDrawable) loadView.getBackground();
        aniDraw.start();
        loading.addContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        loading.setTag(tag);
        loading.setCancelable(true);// 点击返回键关闭
        loading.setCanceledOnTouchOutside(false);// 点击外部关闭
        loading.setOnCancelListener(cancelListener);
        return loading;
    }

    /**
     * 设置TextView分段颜色
     * @param tvContent
     * @param mContext
     */
    public static void setContentColor(TextView tvContent, Context mContext) {
        String strContent = tvContent.getText().toString();
        //SpannableStringBuilder类支持textview改变部分字体颜色和单独设置点击事件，需要的参数只有一个，就是需要显示的文字内容就行，我这里直接从控件获取文本内容了
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(strContent);
        //第一个出现的位置
        final int start = strContent.indexOf("《");
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
                //隐私政策 点击事件
                mContext.startActivity(new Intent(mContext, HsLagelDetailActivity.class).putExtra("type", "4"));
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                //设置文件颜色
                ds.setColor(Color.parseColor("#808081"));
                // 去掉下划线
                ds.setUnderlineText(false);
            }

        }, start, start + 17, 0);
//        //最后一个出现的位置
//        final int end = strContent.lastIndexOf("《");
//        ssb.setSpan(new ClickableSpan() {
//
//            @Override
//            public void onClick(View widget) {
//                //用户注册协议  击事件
//
//                mContext.startActivity(new Intent(mContext, HsLagelDetailActivity.class).putExtra("type", "1"));
//
//            }
//
//            @Override
//            public void updateDrawState(TextPaint ds) {
//                super.updateDrawState(ds);
//                //设置文件颜色
//                ds.setColor(Color.parseColor("#808081"));
//                // 去掉下划线
//                ds.setUnderlineText(false);
//            }
//
//        }, end, end + 6, 0);
        tvContent.setMovementMethod(LinkMovementMethod.getInstance());
        tvContent.setText(ssb, TextView.BufferType.SPANNABLE);

    }
    /**
     * 设置TextView分段颜色
     * @param tvContent
     * @param mContext
     */
    public static void setContentColor(TextView tvContent, Context mContext,int start,int length,String strColor) {
        String strContent = tvContent.getText().toString();
        //SpannableStringBuilder类支持textview改变部分字体颜色和单独设置点击事件，需要的参数只有一个，就是需要显示的文字内容就行，我这里直接从控件获取文本内容了
        SpannableStringBuilder ssb = new SpannableStringBuilder();
        ssb.append(strContent);
        //第一个出现的位置
        ssb.setSpan(new ClickableSpan() {

            @Override
            public void onClick(View widget) {
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                //设置文件颜色
                ds.setColor(Color.parseColor(strColor));
                // 去掉下划线
                ds.setUnderlineText(false);
            }

        }, start, start + length, 0);
        tvContent.setMovementMethod(LinkMovementMethod.getInstance());
        tvContent.setText(ssb, TextView.BufferType.SPANNABLE);

    }

}




